<?php

function ls_files($dir) {
    
    $files  = array();
    
    if (is_dir($dir)) {
        if (($dh = opendir($dir))) {
            while (($file = readdir($dh)) !== false) {
                if ($file !== "." && $file !== "..") {
                    $files[] = realpath($dir . DIRECTORY_SEPARATOR . $file);
                }
            }
            closedir($dh);
        }
    }
    
    return $files;
}


/**
 * 
 * @param PDO $db
 * @param type $searchParams
 * @return \Document
 */
function getDocument(PDO $db, $searchParams)
{
    $keyParams      = array_keys($searchParams);
    $query          = "SELECT * FROM ".  Persistance::$documentTable." ";
    foreach($keyParams as $i => $keyParam)
    {
        $query .= ($i > 0 ? "AND " : "WHERE ").$keyParam." = :".$keyParam;
    }
    
    $stmt = $db->prepare($query);
    $stmt->execute($searchParams);

    $document = new Document;
    if(($row = $stmt->fetch()))
    {
        $document->setDescription($row["description"])
                ->setIcone($row["icone"])
                ->setId($row["id"])
                ->setLongueur($row["longueur"])
                ->setPath($row["path"])
                ->setTitre($row["titre"]);
    }

    return $document;
}

/**
 *
 * @param PDO $db
 * @param string $rech
 * @return indexClass[]
 */
function search(PDO $db, $rech){
    $indexer    = new IndexerV1();
    $terms      = array_map(function($recherche) {
        return mysql_real_escape_string($recherche["term"]);
    }, $indexer->wordsToTerm($rech));

    /*
    $recherche=explode(" ", strtolower($rech));
    
    //Création d'une liste de termes en ignorant les termes issus de la stop list
    $terms = array();
    foreach($recherche as $mot){
        if(($key = array_search($mot, $stoplist)) !== false) {
            unset($recherche[$key]);
        }else
        {
            $terms[] = mysql_real_escape_string($indexer->wordToTerm($mot));
        }
    }*/

//    $tronc=$indexer->wordToTerm($recherche2[0]);
    $sql =  "SELECT * FROM `index` WHERE terme IN('".implode("','", $terms)."') ORDER BY poids DESC;";
//    $first=true;
//    foreach($recherche2 as $mot){
//        if(!$first){
//            $tronc=$indexer->wordToTerm($mot);
//            $sql.=" OR terme='".mysql_real_escape_string($tronc)."'";
//        }
//        $first=false;
//    }
    
    
    $sql = "SELECT d.id as id, SUM(i.poids) as poids FROM ".Persistance::$documentTable. " d, ".  Persistance::$indexTable." i "
            . "WHERE i.id_document = d.id "
            . "AND i.terme IN('".implode("','", $terms)."') "
            . "GROUP BY id "
            . "ORDER BY poids DESC";
   
    $results=array();
    foreach ($db->query($sql) as $row) {
        //$robertson=$row['poids']/($row['poids']+0.5+1.5*(100/100));
        $idDocument             = $row['id'];
        $document               = getDocument($db, array('id' => $idDocument));
        $results[]              = new indexClass($idDocument, $document, $row['poids']);
    }

    //Calcul de la longueur moyenne des documents
    $longueurMoyenne  = array_reduce($results, function($accu, indexClass $indexClass) {
        $accu += $indexClass->getDocument()->getLongueur();
        return $accu;
    }, 0);

    //Assignation de la pertinence (Robertson-Sparck)
    foreach($results as $indClass)
    {
        $robertson = get_robertson($indClass->getPoids(), $indClass->getDocument(), $longueurMoyenne);
        $indClass->setRobertson($robertson);
    }

    return trier_tab($results);
}

function get_robertson($poids, Document $document, $longueurMoyenne)
{
    $longueurDocument   = intval($document->getLongueur());

//    $longueurDocument   = 100;
//    $longueurMoyenne    = 100;

    $tf = $poids;
    $k  = $poids + 0.5 + 1.5*($longueurDocument / $longueurMoyenne);

    return $tf / ($k + $tf);
}


function trier_tab($results){
    
    //Tri selon le score de Robertson-Sparck
    usort($results,function(indexClass $cmp1, indexClass $cmp2){
        if($cmp1->robertson == $cmp2->robertson ){
            return 0;
        }
        return ($cmp1->robertson < $cmp2->robertson)?1:-1;
    });
    
    return $results;

    /*
    $tab2 = array();
    foreach ($tab as $indclass){
        $exist=false;
        foreach($tab2 as $indclass2){
            if($indclass2->getDocument()->getId() == $indclass->getDocument()->getId()){
                $exist=true;
                break;
            }
        }
        if (!$exist) {
            $tab2[] = $indclass;
        }
    }*/

    //return $tab2;
}
